package com.slz.crm.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slz.crm.common.exiception.BaseException;
import com.slz.crm.common.untils.BaseUnit;
import com.slz.crm.pojo.dto.ContactTaskDTO;
import com.slz.crm.pojo.entity.ContactTaskEntity;
import com.slz.crm.pojo.entity.CustomerCompanyEntity;
import com.slz.crm.pojo.entity.CustomerContactEntity;
import com.slz.crm.pojo.entity.SalesOpportunityEntity;
import com.slz.crm.pojo.entity.UserEntity;
import com.slz.crm.pojo.vo.ContactTaskVO;
import com.slz.crm.server.constant.MessageConstant;
import com.slz.crm.server.mapper.ContactTaskMapper;
import com.slz.crm.server.mapper.CustomerCompanyMapper;
import com.slz.crm.server.mapper.CustomerContactMapper;
import com.slz.crm.server.mapper.SalesOpportunityMapper;
import com.slz.crm.server.mapper.UserMapper;
import com.slz.crm.server.service.ContactTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ContactTaskServiceImpl extends ServiceImpl<ContactTaskMapper, ContactTaskEntity> implements ContactTaskService {

    @Autowired
    private ContactTaskMapper contactTaskMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CustomerCompanyMapper customerCompanyMapper;

    @Autowired
    private CustomerContactMapper customerContactMapper;

    @Autowired
    private SalesOpportunityMapper salesOpportunityMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(ContactTaskDTO contactTaskDTO) {
        if (contactTaskDTO == null || contactTaskDTO.getTaskTitle() == null) {
            throw new BaseException(MessageConstant.PARAM_ERROR);
        }

        ContactTaskEntity contactTaskEntity = new ContactTaskEntity();
        BeanUtils.copyProperties(contactTaskDTO, contactTaskEntity);

        Long currentId = BaseUnit.getCurrentId();
        contactTaskEntity.setCreatorId(currentId);
        contactTaskEntity.setCreateTime(new Date());
        contactTaskEntity.setUpdateTime(new Date());

        // 设置默认状态为未开始
        if (contactTaskEntity.getStatus() == null) {
            contactTaskEntity.setStatus(0);
        }

        // 设置默认优先级
        if (contactTaskEntity.getPriority() == null) {
            contactTaskEntity.setPriority(5);
        }

        return save(contactTaskEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteByIds(List<Long> idList) {
        if (idList == null || idList.isEmpty()) {
            throw new BaseException(MessageConstant.ID_LIST_IS_NULL);
        }
        return contactTaskMapper.deleteBatchIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        if (id == null) {
            throw new BaseException(MessageConstant.ID_ERROR);
        }
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateList(List<ContactTaskDTO> contactTaskDTOList) {
        if (contactTaskDTOList == null || contactTaskDTOList.isEmpty()) {
            throw new BaseException(MessageConstant.DATA_IS_NULL);
        }

        List<ContactTaskEntity> entityList = new ArrayList<>();
        for (ContactTaskDTO dto : contactTaskDTOList) {
            ContactTaskEntity entity = new ContactTaskEntity();
            BeanUtils.copyProperties(dto, entity);
            entity.setUpdateTime(new Date());
            entityList.add(entity);
        }

        return updateBatchById(entityList) ? entityList.size() : 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(ContactTaskDTO contactTaskDTO) {
        if (contactTaskDTO == null || contactTaskDTO.getId() == null) {
            throw new BaseException(MessageConstant.PARAM_ERROR);
        }

        ContactTaskEntity entity = new ContactTaskEntity();
        BeanUtils.copyProperties(contactTaskDTO, entity);
        entity.setUpdateTime(new Date());

        return updateById(entity);
    }

    @Override
    public ContactTaskVO getById(Long id) {
        if (id == null) {
            throw new BaseException(MessageConstant.ID_ERROR);
        }

        ContactTaskEntity entity = contactTaskMapper.selectById(id);
        if (entity == null) {
            throw new BaseException(MessageConstant.DATA_IS_NULL);
        }

        return convertToVO(entity);
    }

    @Override
    public Page<ContactTaskVO> getAll(Integer pageNum, Integer pageSize) {
        Page<ContactTaskEntity> page = new Page<>(pageNum, pageSize);
        Page<ContactTaskEntity> pageResult = page(page, new LambdaQueryWrapper<ContactTaskEntity>()
                .orderByDesc(ContactTaskEntity::getCreateTime));

        Page<ContactTaskVO> resultPage = new Page<>();
        BeanUtils.copyProperties(pageResult, resultPage);

        List<ContactTaskVO> voList = new ArrayList<>();
        for (ContactTaskEntity entity : pageResult.getRecords()) {
            voList.add(convertToVO(entity));
        }
        resultPage.setRecords(voList);

        return resultPage;
    }

    @Override
    public Page<ContactTaskVO> query(Integer pageNum, Integer pageSize, ContactTaskDTO contactTaskDTO) {
        Page<ContactTaskEntity> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ContactTaskEntity> wrapper = new LambdaQueryWrapper<>();

        if (contactTaskDTO != null) {
            if (contactTaskDTO.getTaskTitle() != null) {
                wrapper.like(ContactTaskEntity::getTaskTitle, contactTaskDTO.getTaskTitle());
            }
            if (contactTaskDTO.getCompanyId() != null) {
                wrapper.eq(ContactTaskEntity::getCompanyId, contactTaskDTO.getCompanyId());
            }
            if (contactTaskDTO.getContactId() != null) {
                wrapper.eq(ContactTaskEntity::getContactId, contactTaskDTO.getContactId());
            }
            if (contactTaskDTO.getOpportunityId() != null) {
                wrapper.eq(ContactTaskEntity::getOpportunityId, contactTaskDTO.getOpportunityId());
            }
            if (contactTaskDTO.getTaskType() != null) {
                wrapper.eq(ContactTaskEntity::getTaskType, contactTaskDTO.getTaskType());
            }
            if (contactTaskDTO.getPriority() != null) {
                wrapper.eq(ContactTaskEntity::getPriority, contactTaskDTO.getPriority());
            }
            if (contactTaskDTO.getStatus() != null) {
                wrapper.eq(ContactTaskEntity::getStatus, contactTaskDTO.getStatus());
            }
            if (contactTaskDTO.getAssigneeId() != null) {
                wrapper.eq(ContactTaskEntity::getAssigneeId, contactTaskDTO.getAssigneeId());
            }
        }

        wrapper.orderByDesc(ContactTaskEntity::getCreateTime);
        Page<ContactTaskEntity> pageResult = page(page, wrapper);

        Page<ContactTaskVO> resultPage = new Page<>();
        BeanUtils.copyProperties(pageResult, resultPage);

        List<ContactTaskVO> voList = new ArrayList<>();
        for (ContactTaskEntity entity : pageResult.getRecords()) {
            voList.add(convertToVO(entity));
        }
        resultPage.setRecords(voList);

        return resultPage;
    }

    @Override
    public List<ContactTaskVO> getByAssigneeId(Long assigneeId) {
        if (assigneeId == null) {
            return new ArrayList<>();
        }

        List<ContactTaskEntity> entities = list(new LambdaQueryWrapper<ContactTaskEntity>()
                .eq(ContactTaskEntity::getAssigneeId, assigneeId)
                .orderByDesc(ContactTaskEntity::getCreateTime));

        List<ContactTaskVO> voList = new ArrayList<>();
        for (ContactTaskEntity entity : entities) {
            voList.add(convertToVO(entity));
        }

        return voList;
    }

    @Override
    public List<ContactTaskVO> getByCompanyId(Long companyId) {
        if (companyId == null) {
            return new ArrayList<>();
        }

        List<ContactTaskEntity> entities = list(new LambdaQueryWrapper<ContactTaskEntity>()
                .eq(ContactTaskEntity::getCompanyId, companyId)
                .orderByDesc(ContactTaskEntity::getCreateTime));

        List<ContactTaskVO> voList = new ArrayList<>();
        for (ContactTaskEntity entity : entities) {
            voList.add(convertToVO(entity));
        }

        return voList;
    }

    @Override
    public List<ContactTaskVO> getByContactId(Long contactId) {
        if (contactId == null) {
            return new ArrayList<>();
        }

        List<ContactTaskEntity> entities = list(new LambdaQueryWrapper<ContactTaskEntity>()
                .eq(ContactTaskEntity::getContactId, contactId)
                .orderByDesc(ContactTaskEntity::getCreateTime));

        List<ContactTaskVO> voList = new ArrayList<>();
        for (ContactTaskEntity entity : entities) {
            voList.add(convertToVO(entity));
        }

        return voList;
    }

    @Override
    public List<ContactTaskVO> getByOpportunityId(Long opportunityId) {
        if (opportunityId == null) {
            return new ArrayList<>();
        }

        List<ContactTaskEntity> entities = list(new LambdaQueryWrapper<ContactTaskEntity>()
                .eq(ContactTaskEntity::getOpportunityId, opportunityId)
                .orderByDesc(ContactTaskEntity::getCreateTime));

        List<ContactTaskVO> voList = new ArrayList<>();
        for (ContactTaskEntity entity : entities) {
            voList.add(convertToVO(entity));
        }

        return voList;
    }

    /**
     * 将Entity转换为VO，并设置关联信息
     */
    private ContactTaskVO convertToVO(ContactTaskEntity entity) {
        ContactTaskVO vo = new ContactTaskVO();
        BeanUtils.copyProperties(entity, vo);

        // 设置创建人姓名
        if (entity.getCreatorId() != null) {
            UserEntity creator = userMapper.selectById(entity.getCreatorId());
            if (creator != null) {
                vo.setCreatorName(creator.getRealName());
            }
        }

        // 设置执行人姓名
        if (entity.getAssigneeId() != null) {
            UserEntity assignee = userMapper.selectById(entity.getAssigneeId());
            if (assignee != null) {
                vo.setAssigneeName(assignee.getRealName());
            }
        }

        // 设置公司名称
        if (entity.getCompanyId() != null) {
            CustomerCompanyEntity company = customerCompanyMapper.selectById(entity.getCompanyId());
            if (company != null) {
                vo.setCompanyName(company.getCompanyName());
            }
        }

        // 设置联系人姓名
        if (entity.getContactId() != null) {
            CustomerContactEntity contact = customerContactMapper.selectById(entity.getContactId());
            if (contact != null) {
                vo.setContactName(contact.getName());
            }
        }

        // 设置销售机会标题
        if (entity.getOpportunityId() != null) {
            SalesOpportunityEntity opportunity = salesOpportunityMapper.selectById(entity.getOpportunityId());
            if (opportunity != null) {
                vo.setOpportunityTitle(opportunity.getOpportunityName());
            }
        }

        return vo;
    }
}